package com.me.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.anno.RequireLogin;
import com.me.bbs.common.Resp;
import com.me.bbs.common.SessionUtils;
import com.me.bbs.dto.PostCollectionDTO;
import com.me.bbs.dto.PostDTO;
import com.me.bbs.entity.Post;
import com.me.bbs.entity.PostCollection;
import com.me.bbs.service.ICollectionService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lm
 * @since 2023-01-16
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {
    @Resource
    ICollectionService collectionService;
    @PostMapping("/{postId}")
    @RequireLogin
    public Resp<?> addCollection(@PathVariable Long postId) throws Exception {
        collectionService.saveCollection(postId);
        return Resp.success();
    }

    @DeleteMapping("/{postId}")
    @RequireLogin
    public Resp<?> deleteCollection(@PathVariable Long postId) throws Exception {
        collectionService.delCollection(postId);
            return Resp.success();
    }

    @PostMapping("/getCollectionByUser")
    @RequireLogin
    public Resp<?> getCollectionByUser(@RequestParam("current") Long current,
                                       @RequestParam("size") Long size
                                   ) {
        Page<PostCollectionDTO> page = new Page<>(current, size);
        LambdaQueryWrapper<PostCollection> wrapper = new LambdaQueryWrapper<>();
        Long userId = (Long) SessionUtils.getAttribute("user");
        wrapper.eq(userId != null,PostCollection::getUser, userId)
                .orderByDesc(PostCollection::getCreateAt);
        Page<PostCollectionDTO> collectionDTOPage = collectionService.getCollectionByUser(page, wrapper);
        return Resp.success(collectionDTOPage, "成功");
    }

}
